package com.example.administrator.funchat.fragment;

import android.app.Fragment;
import android.app.ProgressDialog;
import android.content.Context;
import android.content.Intent;
import android.net.ConnectivityManager;
import android.os.Bundle;
import android.os.Handler;
import android.support.annotation.Nullable;
import android.util.Log;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Toast;

import com.example.administrator.funchat.R;
import com.example.administrator.funchat.activity.MainActivity;
import com.example.administrator.funchat.activity.RegisterLoginActivity;
import com.example.administrator.funchat.model.User;
import com.example.administrator.funchat.util.WebService;
import com.google.gson.Gson;

import java.util.Map;

/**
 * Created by Administrator on 2016/6/21.
 */
public class LoginFragment extends Fragment implements View.OnClickListener {

    // 返回的数据
    private String info;
    //登录按钮
    private Button logoBtton;
    //输入框
    private EditText username, password;
    //进度条
    private ProgressDialog dialog;
    // 返回主线程更新数据
    private static Handler handler = new Handler();
    //注册成功后的参数
    public Map<String, String> params = null;
    private User user;

    public static String userPhone;

    @Nullable
    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        View view = inflater.inflate(R.layout.login_fragment, container, false);
        //初始化数据
        username = (EditText) view.findViewById(R.id.loginPhone);
        password = (EditText) view.findViewById(R.id.loginPassWord);
        if (params != null) {
            username.setText(params.get("phone"));
            password.setText(params.get("password"));
        }
        logoBtton = (Button) view.findViewById(R.id.denglu_button);
        //设置登录按钮点击事件
        logoBtton.setOnClickListener(this);
        return view;
    }

    @Override
    public void onClick(View view) {
        if (!checkNetwork(view)) {
            Toast toast = Toast.makeText(view.getContext(), "网络未连接", Toast.LENGTH_SHORT);
            toast.setGravity(Gravity.CENTER, 0, 0);
            toast.show();
        }
        //弹出对话框
        dialog = new ProgressDialog(view.getContext());
        dialog.setMessage("正在登录，请稍后....");
        dialog.setCancelable(false);
        dialog.show();
        //创建子线程
        new Thread(new MyThread()).start();

    }

    //创建子线程,分别进行Get和Post传输
    private class MyThread implements Runnable {
        @Override
        public void run() {
            //请求数据
            String address = "/MyChat/UserServlet?options=login" + "&phone=" + username.getText().toString() + "&password=" + password.getText().toString();
            info = WebService.executeHttpGet(address);
            handler.post(new Runnable() {
                @Override
                public void run() {
                    if (info == null) {
                        dialog.dismiss();
                        Toast toast = Toast.makeText(getActivity(), "登录失败,无法连接到服务器", Toast.LENGTH_SHORT);
                        toast.setGravity(Gravity.CENTER, 0, 0);
                        toast.show();
                    } else if (info.equals("error")) {
                        dialog.dismiss();
                        Toast toast = Toast.makeText(getActivity(), "手机或密码错误", Toast.LENGTH_SHORT);
                        toast.setGravity(Gravity.CENTER, 0, 0);
                        toast.show();

                    } else {
                        dialog.dismiss();
                        Log.i("login", "run: " + info);
                        user = new Gson().fromJson(info, User.class);//json序列化
                        Log.i("login", "run: " + user.getPhone());
                        userPhone = username.getText().toString();
                        Intent intent = new Intent(getActivity(), MainActivity.class);
                        intent.putExtra("info", user);
                        startActivity(intent);
                        RegisterLoginActivity activity = (RegisterLoginActivity) getActivity();
                        activity.finish();
                    }

                }
            });
        }
    }

    //检查是否存在网络
    private boolean checkNetwork(View view) {
        ConnectivityManager connManager = (ConnectivityManager) view.getContext().getSystemService(Context.CONNECTIVITY_SERVICE);
        if (connManager.getActiveNetworkInfo() != null) {
            return connManager.getActiveNetworkInfo().isAvailable();
        }
        return false;
    }
}
